<template>
  <div>
    <!-- 导入文件 -->
    <input type="file" webkitdirectory v-show="false" ref="inputFile" multiple @change="handleFileUpload">

    <el-dialog :close-on-click-modal="false" v-model="dialogVisible" title="上传文件夹" width="55%" :before-close="handleClose" append-to-body>
      <div v-if="false" class="file-uploader" @dragover.prevent @dragenter.prevent @dragleave.prevent @drop.prevent="handleDrop">
        <div class="flex alignCenter justifyCenter">
          <el-icon size="70">
            <UploadFilled />
          </el-icon>
        </div>
        <div class="flex alignCenter justifyCenter text">
          <text v-if="false">拖拽文件夹到此区域进行上传 或</text>
          <span style="margin-left: 5px;" @click="proxy.$refs.inputFile.click()">点击上传</span>
        </div>
      </div>

      <div class="actionBtn">
        <el-button type="primary" :loading="loading" @click="proxy.$refs.inputFile.click()">上传文件夹</el-button>
        <el-button type="primary" plain @click="exportExcel">导出</el-button>
      </div>

      <el-table :data="fileList" maxHeight="60vh">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="name" label="文件名" show-overflow-tooltip />
        <el-table-column prop="path" label="文件链接" show-overflow-tooltip />
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="conform">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
let props = defineProps(["modelValue", "dataType"]);
const emit = defineEmits(["update:modelValue", "fatherMethods"]);

let dialogVisible = ref(false);
let fileList = ref([]); // 上传的文件列表
let loading = ref(false);

let open = () => {
  setDefaultValue();
  dialogVisible.value = true;
};

function handleDrop(event) {
  event.preventDefault();
  const files = event.dataTransfer.files;
  if (files.length > 0 && files[0].webkitRelativePath) {
    // 如果拖入的是文件夹，webkitRelativePath 不为空且以'/'开头
    const folder = files[0];
    console.log("Dropped folder:", folder.name);
    // 在这里进行处理拖入的文件夹的逻辑
  } else {
    const files = event.dataTransfer.files;
    console.log("文件上传", files);
  }
  return;
  handleFunc(files);
}

async function exportExcel() {
  let cols = []; //设置表头样式
  let jsonData = []; //设置数据
  fileList.value.forEach((element) => {
    cols.push({ wch: 20 });
    jsonData.push({
      文件名: element.name,
      文件链接: element.path,
    });
  });
  let query = { jsonData, cols };
  await proxy.$utils.exportToExcel(query, "文件链接导出");
}

function handleFileUpload(event) {
  const files = event.target.files;
  handleFunc(files);
}

let handleFunc = async (files) => {
  try {
    loading.value = true;
    for (let index = 0; index < files.length; index++) {
      const element = files[index];
      fileList.value.push({
        name: element.webkitRelativePath
          ? element.webkitRelativePath
          : element.name,
        path: await counter.uploadFile(element),
      });
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
  console.log("上传成功后的 url", fileList.value);
};

let openPreview = (e) => {
  window.open(e, "_blank");
};

let handleClose = () => {
  fileList.value = [];
  emit("fatherMethods");
  dialogVisible.value = false;
};

let conform = () => {
  let list = <any>[];
  fileList.value.forEach((element) => {
    list.push(element.path);
  });
  if (props.dataType == "arr") {
    emit("update:modelValue", list);
  } else if (props.dataType == "jsonArr") {
    emit("update:modelValue", fileList.value);
  } else {
    //字符串
    emit("update:modelValue", list.toString());
  }
  handleClose();
};

function setDefaultValue() {
  if (props.modelValue) {
    let dataType;
    if (props.dataType) {
      dataType = props.dataType;
    } else {
      dataType = isJsonArray(props.modelValue);
    }

    let newValue = proxy.$utils.deepcopy(props.modelValue);
    console.log("设置默认值", newValue);
    let arr = <any>[];
    if (dataType == "arr") {
      //数组
      newValue.forEach((element) => {
        arr.push({ path: element, name: element });
      });
    } else if (dataType == "jsonArr") {
      arr = [...newValue];
    } else {
      let list = newValue.split(",");
      list.forEach((element) => {
        arr.push({ path: element, name: element });
      });
    }
    fileList.value = [...arr];
  }
}

//判断变量的数据类型
function isJsonArray(value) {
  if (Array.isArray(value)) {
    try {
      // 尝试将数组转换为JSON字符串
      JSON.stringify(value);
      // 如果转换没有错误，它是一个JSON数组
      return "jsonArr";
    } catch (e) {
      // 如果转换抛出错误，它不是一个JSON数组
      return "arr";
    }
  } else {
    // 如果不是数组，它肯定不是JSON数组
    return "string";
  }
}

watch(
  () => props.modelValue,
  (newValue, oldValue) => {
    if (newValue) setDefaultValue();
  },
  { immediate: true, deep: true }
);

defineExpose({ open });
</script>



<style lang="scss" scoped>
.file-uploader {
  border: 2px dashed #ccc;
  border-radius: 10px;
  padding: 50px 0;

  .text {
    margin-top: 15px;
  }

  span {
    color: #409eff;
    cursor: pointer;
  }
}

.actionBtn {
  margin-bottom: 15px;
}

.file-list {
  margin-top: 10px;

  .box:hover {
    background-color: #f5f7fa;

    .name {
      color: #409eff;
    }

    .del {
      color: #409eff;
      display: block !important;
      cursor: pointer;
    }
  }

  .box {
    background-color: #ffffff;
    padding: 5px;
    border-radius: 5px;
    transition: transform 0.2s ease;

    .name {
      span {
        margin-left: 5px;
      }
    }

    .del {
      display: none;
    }
  }
}
</style>
